package cn.edu.swu.miniwebsvr.core;

import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;


public class HttpParser {
    private Config config;
    public HttpParser(Config config) {
        this.config = config;
    }

    public void setConfig(Config config) {
        this.config = config;
    }

    public static Parameter parse(InputStream inputStream) throws IOException {
        Parameter parameter = new Parameter();

        BufferedReader input = new BufferedReader(new InputStreamReader(inputStream));


        // 读取并解析 HTTP 请求行
        String requestLine = input.readLine();
        System.out.println("请求行："+requestLine);
        if (requestLine == null || requestLine.isEmpty()) {
            return parameter;
        }
        parseRequestLine(requestLine,parameter);

        // 解析HTTP请求头
        parseHeaders(input,parameter);

        // 解析请求体，根据请求方法 (Method) 和请求头 (Content-Length, Content-Type)
        parseRequestBody(input,parameter);

         return parameter;
    }

    private static void parseRequestLine(String requestLine, Parameter parameter) {
        /**
         * 解析请求
         * 标准HTTP请求格式e.g.:GET /index.html?param=value HTTP/1.1
         * 按照空格分割，得到字符串数组（三个元素）
         */
        String[] requestParts = requestLine.split(" ");
        if (requestParts.length < 3) {
            return;
        }
        // 设置请求方法
        parameter.setMethod(requestParts[0]);

        // 解析URL和查询参数
        String url = requestParts[1];
        parseUrlAndQueryParams(url,parameter);

    }

    private static void parseUrlAndQueryParams(String url,Parameter parameter) {
        int queryIndex = url.indexOf('?');

        if (queryIndex >=0) {
            parameter.setUrl(url.substring(0,queryIndex));
            String queryString = url.substring(queryIndex+1);
            parseQueryString(queryString,parameter);
        } else {
            parameter.setUrl(url);
        }
    }

    private static void parseQueryString(String queryString, Parameter parameter) {
        if (queryString == null || queryString.isEmpty()) {
            return;
        }
        String[] QueryPairs = queryString.split("&");
        for (String pair : QueryPairs) {
            int separator = pair.indexOf('=');
            if (separator > 0) {
                try {
                    String key = pair.substring(0,separator);
                    String value = pair.substring(separator + 1);
                    parameter.setUrlParams(key,value);
                } catch (Exception e){

                }
            } else if (separator == 0) {
                try {
                    String value = pair.substring(1);
                    parameter.setUrlParams("",value);
                } catch (Exception e){

                }
            } else {
                try {
                    String key = pair;
                    parameter.setUrlParams(key,"");
                } catch (Exception e) {

                }
            }
        }
    }

    public static void parseHeaders(BufferedReader input, Parameter parameter) throws IOException{
        String line;
        while ((line = input.readLine()) !=null) {
            if (line.isEmpty()) {
                break;
            }

            int separator = line.indexOf(':');
            if (separator > 0) {
                String key = line.substring(0, separator).trim(); // 去除空白
                String value = line.substring(separator+1).trim();
                parameter.setHeaders(key, value);
            }
        }
    }

    private static void parseRequestBody(BufferedReader input,Parameter parameter) throws IOException {
        // 检查是否为POST请求
        if (!"POST".equalsIgnoreCase(parameter.getMethod())) {
            return;
        }
        // 检查contentLength
        String contentLengthHeader = parameter.getParam("Content-Length");
        if (contentLengthHeader == null) {
            return;
        }

        try {
            int contentLength = Integer.parseInt(contentLengthHeader);
            if (contentLength <= 0){
                return;
            }
            // 获取请求体
            char[] bodyChars = new char[contentLength];
            int byteRead = input.read(bodyChars,0,contentLength);
            if (byteRead > 0) {
                String body = new String(bodyChars,0,byteRead);

                // 查看请求体
                String contentType = parameter.getParam("Content-Type");
                if (contentType != null && contentType.contains("application/x-www-form-urlencoded")) {
                    parseQueryString(body, parameter);
                }
            }



        } catch (NumberFormatException e) {

        }
    }


}
